package com.ow.dva.module.version.service.impl;

import cn.hutool.core.io.FileUtil;
import com.ow.dva.module.version.entity.Version;
import com.ow.dva.module.version.mapper.VersionMapper;
import com.ow.dva.module.version.service.VersionService;
import com.ow.dva.module.base.service.impl.DvaServiceImpl;
import com.ow.dva.util.UUIDFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ow.dva.module.base.entity.param.DvaPage;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;

/**
 * <p>
 * 版本更新（路侧App） 服务实现类
 * </p>
 *
 * @author YanZengBao
 * @since 2020-04-20
 * @version V1.0
 */
@Service
public class VersionServiceImpl extends DvaServiceImpl<VersionMapper, Version> implements VersionService {

    @Value("${dva.static-path}")
    private String staticPath;

    @Override
    public DvaPage<Version> page(DvaPage<Version> page, Map<String, Object> param) {

        return baseMapper.page(page,param);
    }

    @Override
    public Version getNewVersion(Version version) {
        return baseMapper.getNewVersion(version);
    }

    @Override
    public int count(Map<String, Object> param) {
        return baseMapper.count(param);
    }

    @Override
    public String fileUpload(MultipartFile file) throws IOException {
        //获取保存目录
        String staticPath = getStaticPath("/version");
        // 获取文件相对路径以及要保存的文件名
        String filename = file.getOriginalFilename();
        String url = "/sion_" + System.currentTimeMillis() + "_" +
                UUIDFactory.getStringId() + "." + filename.substring(filename.lastIndexOf(".") + 1);
        String relativePath = generateFileName(staticPath,url);
        //保存文件到绝对路径
        file.transferTo(new File(staticPath + relativePath));
        return "/version" +url;
    }

    /**
     * @param relativeDir 相对路径
     * @return
     */
    public String getStaticPath(String relativeDir) {
        // 配置路径
        if(staticPath.equals("auto")){
            try {
                staticPath = FileUtil.file(".", relativeDir).getCanonicalPath();
                return staticPath;
            } catch (IOException e) {
                e.printStackTrace();
                return staticPath ;
            }
        }
        return staticPath ;
    }

    //验证文件夹，如果文件夹不存在则创建
    public String createDateDir(String dir) {
        File file = new File( dir);
        if  (!file .exists()  && !file .isDirectory()) {
            file .mkdirs();
        }
        return dir;
    }

    /**
     * 获取文件路径
     * @param staticPath 绝对路径
     * @param filename
     * @return 文件相对路径
     */
    public String generateFileName(String staticPath,String filename) {
//        如果文件夹不存在则创建
        createDateDir(staticPath + "/");
        return "/" + filename;
    }



    public void downFile(HttpServletResponse response, String realPath) throws IOException {
        if(!"".equals(realPath)){
            File file  = new File(realPath);
            if(file.exists()){
                outputStream(response,file,file.getName());
            }
        }
    }

    private void outputStream(HttpServletResponse response, File file,String fileName) throws IOException {
        InputStream in = new FileInputStream(file);
        response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        response.addHeader("Content-Length", "" + file.length());
        OutputStream os = response.getOutputStream();
        byte[] b = new byte[1024];
        while( in.read(b)!= -1){
            os.write(b);
        }
        in.close();
        os.flush();
        os.close();
    }
}
